<template>
  <el-dialog
    :title="showTitle"
    :visible="dialogVisible"
    @close="handleClose"
    @open="handleOpen"
  >
    <!-- 表单组件  el-form   label-width设置label的宽度   -->
    <!-- 匿名插槽 -->
    <el-form ref="formRef" label-width="120px" :model="form" :rules="rules">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="form.name" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="form.code" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="form.manager" style="width:80%" placeholder="请选择">
          <el-option v-for="item in peoples" :key="item.id" :value="item.username" :label="item.username" />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="form.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
      </el-form-item>
    </el-form>
    <!-- el-dialog有专门放置底部操作栏的 插槽  具名插槽 -->
    <div slot="footer">
      <el-button type="primary" size="small" @click="handleConfirm">确定</el-button>
      <el-button size="small" @click="handleClose">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { reqGetEmployeeSimple } from '@/api/employees'
import { reqAddDepartments, reqGetDepartDetail, reqUpdateDepartments } from '@/api/departments'
export default {
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    depts: {
      type: Array,
      required: true
    },
    nodeData: {
      type: Object,
      required: true
    }
  },
  data() {
    /**
     * rules：基本不用
     * value: 输入的值
     * callback 不管成功还是失败都会调用
     */
    // 部门名称校验
    const validateName = (rules, value, callback) => {
      let arr
      // 简单版部门名称校验
      //  新增的校验逻辑，找的是父级部门（在父级部门点击添加）的孩子们
      // 修改，点击的是本部门，我们需要找的是兄弟部门
      if (this.form.id) {
        // 如果是编辑操作，可以和原来的code重复
        if (value === this.nodeData.name) {
          return callback()
        }
        arr = this.depts.filter(item => item.pid === this.nodeData.pid)
      } else {
        // 新增 找的是父级部门的孩子们
        arr = this.depts.filter(item => item.pid === this.nodeData.id)
      }

      const isRepeat = arr.some(item => item.name === value)
      isRepeat ? callback(new Error('同级部门中禁止出现重复部门')) : callback()
      // console.log(JSON.parse(JSON.stringify(this.depts)))
      // this.depts.filter(item => item.pid === this.nodeData.id)
      // console.log(arr)
      // const isRepeat = this.depts.some(item => item.name === value)
      // isRepeat ? callback(new Error('部门名称不允许重复')) : callback()
      // console.log(JSON.parse(JSON.stringify(arr)))

      // 基础版校验
      // const isRepeat = this.depts.some(item => item.name === value)
      // isRepeat ? callback(new Error('部门名称不允许重复')) : callback()
    }

    // 部门编码校验
    const validateCode = (rules, value, callback) => {
    //   callback(new Error('错误的'))
    // 编辑功能，允许部门编码重复
      if (this.form.id) {
        // 如果是编辑操作，可以和原来的code重复
        if (value === this.nodeData.code) {
          return callback()
        }
      }
      const isRepeat = this.depts.some(item => item.code === value)
      isRepeat ? callback(new Error('部门编码不允许重复')) : callback()
    }
    return {
      form: {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      },
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: ['blur', 'change'] },
          { min: 1, max: 15, message: '请输入1~15个字符', trigger: ['blur', 'change'] },
          { validator: validateName, trigger: 'blur' }

        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: ['blur', 'change'] },
          { min: 1, max: 15, message: '请输入1~15个字符', trigger: ['blur', 'change'] },
          { validator: validateCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: ['blur', 'change'] },
          { min: 1, max: 15, message: '请输入1~15个字符', trigger: ['blur', 'change'] }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: ['blur', 'change'] },
          { min: 1, max: 300, message: '请输入1~300个字符', trigger: ['blur', 'change'] }
        ]
      },
      peoples: []
    }
  },
  computed: {
    showTitle() {
      return this.form.id ? '编辑部门' : '新增部门'
    }
  },
  created() {
    this.getEmployeeSimple()
  },
  methods: {
    handleClose() {
      // 通知父组件
      // this.$emit('close-dialog', false)
      this.$emit('update:dialogVisible', false)
      // 点编辑，取消会重置数据
      this.form = {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      }
      // 重置表单数据
      this.$refs.formRef.resetFields()
    },
    handleOpen() {
      // this.getEmployeeSimple()
      // console.log('open')
    },
    handleConfirm() {
      this.$refs.formRef.validate(async(valid) => {
        if (valid) {
          // console.log('发送请求新增数据')
          if (this.form.id) {
            // 编辑
            const res = await reqUpdateDepartments(this.form)
            console.log('编辑的数据', res)
            this.$message.success('修改部门数据成功')
          } else {
            // 新增部门
            await reqAddDepartments({
              ...this.form,
              pid: this.nodeData.id
            })
            this.$message.success('新增数据成功')
          }

          // 关闭弹层
          this.handleClose()
          // 通知父组件
          this.$emit('add-depts')
          // console.log(res)
        }
      })
    },
    // 获取简单员工数据列表
    async getEmployeeSimple() {
      const res = await reqGetEmployeeSimple()
      // console.log(res)
      this.peoples = res.data
    },
    async getDepartDetail(id) {
      const { data } = await reqGetDepartDetail(id)
      console.log(data)
      this.form = data
    }
  }
}
</script>

